import React, { useState } from 'react';
import { Modal, Form, Input, Button, message } from 'antd';
import styles from './index.module.less';
import { MyIcon } from '../../Icon/MyIcon';
import { EmailReg } from '../../utils/regex';
import request from '../../server/request';

//actions 
import { setToken } from './Redux/actions';
import { connect } from "react-redux";

const mapState = (store:any)=>({
    token: store.loginInfo.token
});
const mapAction = {
    setToken
}
const FormItem = Form.Item;

interface FCProps {
    setToken: (token: string | null) => any,
    token:undefined | string,
    path:string,
    isLogin:boolean,
    setIsLogin:(isLogin:boolean)=> void
}

const LoginBox: React.FC <FCProps> = ({setToken, token, path, setIsLogin, isLogin }) => {

    const [form] = Form.useForm();
    const [mode, setMode] = useState('signUp');
  const [loginBtn, setLoginBtn] = useState(true);

    // 校验
    const checkEmail = (rules: any, value: any) => {
        if (!value) {
            setLoginBtn(true);
            return Promise.reject('');
        }

        if (!EmailReg.test(value)) {
            setLoginBtn(true);
            return Promise.reject('请输入正确的邮箱');
        }
        const { validateFields } = form;
        if (loginBtn) {
            validateFields(['password']).catch(err => {
                console.error("password error", err);
                return Promise.resolve();
            });
            setLoginBtn(false);
        }

    }
    const checkPasswrod = (rules: any, value: any) => {
        if (!value || value.length < 6) {
          setLoginBtn(true);
          return Promise.reject("");
        }
        const { validateFields } = form;
        if (loginBtn) {
          validateFields(['email']).catch(err => {
            console.error("email error", err);
            return Promise.resolve();
          });
          setLoginBtn(false);
        }
      }
    // style
    const styleControl = (str: string) => {
        if (mode == 'signIn') return " " + str;
        return "";
    }

      //register
  const handleRegister = () => {
    const { getFieldsValue } = form;
    const { email, password } = getFieldsValue();
    request('/register', { email, password }, "post").then(res => {
    //   const 
      setMode('signUp');
    });
  }
  const handleLogin = () => {
    const { getFieldsValue } = form;
    const { email, password } = getFieldsValue();
    request('/login', { email, password }, 'post').then((res: any) => {
      const { token, user } = res;
      if(res.errorKey) throw new Error(res.err);     
      setToken(token);
      localStorage.setItem('token', token);
      localStorage.setItem('userId', user.id);

      setIsLogin(true);
    }).catch(err=>{
        message.error(err.toString())
        
    })
  };

    return (
        <Modal title={null}
            footer={null}
            width={680}
            open={!isLogin}
            onCancel={()=>setIsLogin(true)}
            className={styles['login-box']}
            wrapClassName={styles['main-modal']}
        >
            <div className={styles['left']}>
                <div className={styles['smile']}>
                    {/* <MyIcon className={styles['smile-icon']} type='icon-smile-fill' onClick={() => setMode('signIn')} /> */}
                    <img src="src/assets/panda.png"
                     className={styles['smile-icon']}  
                     onClick={() => setMode('signIn')} 
                     style={{width:'30%'}}
                     alt="" />
                </div>
                <div className={styles['register'] + styleControl(styles['register-show'])}>
                    <div className={styles['title']}>账号注册</div>
                    <div className={styles['input-container']}>
                        <Form form={form} >
                            <FormItem name='email'
                                rules={[
                                    {
                                        validator: checkEmail
                                    }
                                ]}>
                                <Input placeholder="输入邮箱账号" />
                            </FormItem>
                            <FormItem name='password'
                                rules={[
                                    {
                                        validator: checkPasswrod
                                    }
                                ]}
                            >
                                <Input placeholder="输入密码" />
                            </FormItem>
                            <Button disabled={loginBtn} className={styles['button']} onClick={handleRegister} >注册账号</Button>
                        </Form>
                    </div>
                    <div className={styles['agreement']}>
                        <img src="src/assets/pacmen.png" alt="" />
                    </div>
                </div>
            </div>

            <div className={styles['right']}>
                <div className={styles['smile-hide'] + styleControl(styles['icon-show'])}>
                    {/* <MyIcon className={styles['smile-icon']} type='icon-xiaolian' onClick={() => setMode('signUp')} /> */}
                    <img src="src/assets/panda.png"
                     className={styles['smile-icon']}  
                     onClick={() => setMode('signUp')} 
                     style={{width:'30%'}}
                     alt="" />
                </div>
                <div className={styles['login-wrapper'] + styleControl(styles['login-wrapper-hidden'])}>
                    <div className={styles['title']}>邮箱登录</div>
                    <div className={styles['input-container']}>
                        <Form form={form} >
                            <FormItem name='email'
                                rules={[
                                    {
                                        validator: checkEmail

                                    }
                                ]}>
                                <Input placeholder="输入邮箱账号" />
                            </FormItem>
                            <FormItem name='password'
                                rules={[
                                    {
                                        validator: checkPasswrod
                                    }
                                ]}
                            >
                                <Input placeholder="输入密码" />
                            </FormItem>
                            <Button disabled={loginBtn} className={styles['button']} onClick={handleLogin} >登录</Button>
                        </Form>
                    </div>
                    <div className={styles['agreement']}>
                        <img src="src/assets/pacmen.png" alt="" />
                    </div>
                </div>
            </div>
        </Modal>
    )
}
// export default LoginBox;
export default connect(mapState, mapAction)(LoginBox);